package com.echo.tsxStudy.soleDemo;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.request.ContentStreamUpdateRequest;
import org.apache.solr.client.solrj.request.FieldAnalysisRequest;
import org.apache.solr.client.solrj.response.AnalysisResponseBase.AnalysisPhase;
import org.apache.solr.client.solrj.response.AnalysisResponseBase.TokenInfo;
import org.apache.solr.client.solrj.response.FieldAnalysisResponse;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.response.UpdateResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.junit.Test;

import com.spatial4j.core.io.GeohashUtils;

public class SolrJTest {
	//  private static String baseUrl = "http://192.168.7.140:8080/solr/yiwei_core";  
   private static String baseUrl = "http://192.168.7.133:8888/solr/echo_core";  
   public static final SolrClient server = new HttpSolrClient.Builder(baseUrl).build();  
//集群
//String zkHostString = "zkServerA:2181,zkServerB:2181,zkServerC:2181/solr";
//SolrClient solr = new CloudSolrClient.Builder().withZkHost(zkHostString).build();
 
   /** 
    * @Description: 查询关键字 
    * </p> 
    */  
   @Test  
   public void testSoleJ(){  
       try {  
           SolrQuery query = new SolrQuery("provinceId:410000");
           query.setStart(0);
           query.setRows(30);
           query.setSort("cityCode",SolrQuery.ORDER.desc);
        //   query.setSort("city",SolrQuery.ORDER.desc);
           QueryResponse resp = server.query(query);  
          SolrDocumentList list = resp.getResults();
       //  List<SolrModel> list=    resp.getBeans(SolrModel.class);
           System.out.println(list.size());
             for (SolrDocument solrDocument : list) {
				System.out.println(solrDocument);
			}
           System.err.println(resp.getQTime());
       } catch (Exception e) {  
           e.printStackTrace();  
       }  
   }  
   
   
   @Test
   public  void addDocumentfromSolrJ() throws SolrServerException, IOException{
	  List<Map<String, Object>> list = new JdbcTempletEcho().queryDateTempletForList("SELECT city_id   cityId,city,city_code cityCode,province_id provinceId,sort_weight sortWeight,admin_id adminId ,  create_time createTime, last_modify_time lastModifyTime,del_flag delFlag ,note  FROM `cities` limit 11,10 ", null, null);
	  List<SolrInputDocument> listsolr =new ArrayList<SolrInputDocument>();
	  for(int i=0;i<list.size();i++){
		   SolrInputDocument document = new SolrInputDocument();
		   document.addField("id",list.get(i).get("cityId")+"lbs");
		   document.addField("cityId", list.get(i).get("cityId"));
		   document.addField("city", list.get(i).get("city"));
		   document.addField("cityCode", list.get(i).get("cityCode"));
		   document.addField("provinceId", list.get(i).get("provinceId"));
		   document.addField("sortWeight", list.get(i).get("sortWeight"));
		   document.addField("adminId", list.get(i).get("adminId"));
		   document.addField("createTime", list.get(i).get("createTime"));
		   document.addField("lastModifyTime", list.get(i).get("lastModifyTime"));
		   document.addField("delFlag", i);
		   document.addField("note", list.get(i).toString());
		   String geoHash = GeohashUtils.encodeLatLon(113.66609+(i*2+2), 34.75247+(i*2+3));
		   System.out.println(geoHash+list.get(i).get("cityId"));
		   double   latitude=39.869664;
		   double   longitude=116.38325;
		   document.addField("geohostcar", latitude+(i*2+2)+","+longitude+(i*2+3));
		   listsolr.add(document);
	   }
	  UpdateResponse response = server.add(listsolr);
	  server.commit();
	  System.out.println(response.getQTime()+"---"+response.getStatus()); 
   }
   
   
   public static List<String> getFieldDefaultAnalysis(String tokenField, String content) {  
	    FieldAnalysisRequest request = new FieldAnalysisRequest("/analysis/field");  
	    request.addFieldName(tokenField);// 字段名，随便指定一个支持中文分词的字段  
	    request.setFieldValue("");// 字段值，可以为空字符串，但是需要显式指定此参数  
	    request.setQuery(content);  
	  
	    FieldAnalysisResponse response = null;  
	    try {  
	        response = request.process(server);  
	    } catch (Exception e) {  
	        e.printStackTrace();  
	    }  
	  
	    List<String> results = new ArrayList<String>();  
	    Iterator<AnalysisPhase> it = response.getFieldNameAnalysis(tokenField).getQueryPhases().iterator();  
	    while (it.hasNext()) {  
	        AnalysisPhase pharse = (AnalysisPhase) it.next();  
	        List<TokenInfo> list = pharse.getTokens();  
	        for (TokenInfo info : list) {  
	            results.add(info.getText());  
	        }  
	    }  
	  
	    return results;  
	}  
   
     /***
      * 中文分词测试
      */
   @Test
   public  void fieldTestAnalysis(){
	    String content="空山不见人，但闻人语响。";
	   List<String> list = getFieldDefaultAnalysis("analyzerCN", content);
	   
	   System.out.println(list);
	   
   }
   
   @Test
   public  void  lbsgeobash() throws SolrServerException, IOException{
	   double   latitude=39.869664;
	   double   longitude=116.38325;
	   SolrQuery query = new SolrQuery();
	    query.addFilterQuery("{!geofilt}"); 
	   query.set("q", "*:*"); 
	   query.set("d","1000"); //搜索半径 KM 
	   query.set("sfield","geohostcar"); //);//存储地理位置的字段名称
	   query.set("pt",latitude+(1*2+2)+","+longitude+(1*2+3));  //经纬度参数格式为  纬度 X -+180 ,经度Y  -+90
	   QueryResponse rsp = server.query(query);
	   SolrDocumentList list = rsp.getResults();
       //  List<SolrModel> list=    resp.getBeans(SolrModel.class);
           System.out.println(list.size());
             for (SolrDocument solrDocument : list) {
				System.out.println(solrDocument);
			}
   }
   
   
 //单个文件索引
   public  static  void indexFromFile(String fileName,int id,String author,String title) throws Exception{
           //ContentStreamUpdateRequest 是专门用来提交文件的
           ContentStreamUpdateRequest  request=new ContentStreamUpdateRequest("/update/extract");
           String contentType="application/octet-stream";

           request.addFile(new File(fileName), contentType);
          //literal.xxx 文件以外的字段，xxx将直接映射到schema.xml中的同名字段
           request.setParam("literal.id", String.valueOf(id));  
           request.setParam("literal.author", author);  
           request.setParam("literal.title",title);  

       //    request.setAction(AbstractUpdateRequest.ACTION.OPTIMIZE, true, true);   
           server.request(request);

           server.commit();

       }

   
   public static void main(String[] args)  {
       try{
    	   indexFromFile("e:/Apache_Shiro.pdf", 1, "Justn", "solr-ref");
       }catch(Exception e){
           e.printStackTrace();
       }
       }
   
   
}
